package util

import (
	"os"
	"path"

	"github.com/gookit/goutil/fsutil"
)

type ProcessFileFunc func(filepath string, content string, parentDir string)
type ProcessDirFunc func(dirName string, parentDir string)
type FileFilter func(fileName string) bool

func ProcessAny(filePath string, parentDir string, fun ProcessFileFunc, fun2 ProcessDirFunc, fileAccepted FileFilter, dirAccepted FileFilter) {
	filePath = fsutil.Realpath(filePath)
	if !fsutil.PathExists(filePath) {
		return
	}
	if fsutil.IsDir(filePath) {
		if !dirAccepted(filePath) {
			return
		}
		fun2(filePath, parentDir)
		files, err := os.ReadDir(filePath)
		if err != nil {
			panic(err)
		}
		for _, f := range files {
			fileName := f.Name()
			subFullName := path.Join(filePath, fileName)
			ProcessAny(subFullName, filePath, fun, fun2, fileAccepted, dirAccepted)
		}
	} else {
		if fileAccepted(filePath) {
			processOneFile(filePath, fun, parentDir)
		}
	}
}
func processOneFile(fileFullName string, fun ProcessFileFunc, parentDir string) {
	content, err := os.ReadFile(fileFullName)
	if err != nil {
		panic(err)
	}
	fun(fileFullName, string(content), parentDir)
}
